import { isValidToken } from './check';
import { QuestionInput } from './interface';
import { getData, setData } from './dataStore';

function randomColor(): string {
    // 生成三个0到255之间的随机数
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    // 将这三个随机数格式化为CSS中的RGB颜色格式
    return `rgb(${r}, ${g}, ${b})`;
}
import { Data, Session } from "./interface"

import { createHmac } from 'crypto';

export const salt = "盐";
export function hashPassword(password: any) {
    let hash = createHmac('sha256', salt).update(password).digest('hex');
    return hash;
}


export function createQuizQuestion(token: string, quizId: number, questionData: QuestionInput) {
    if (!token) {
        return { error: 'Token is empty or invalid (does not refer to valid logged in user session)' };
    }
    const userId = isValidToken(token);
    if (!userId) {
        return { error: 'Token is empty or invalid (does not refer to valid logged in user session)' };
    }

    const data = getData();
    const quiz = data.quizzes.find(q => q.QuizID === quizId);
    if (!quiz) {
        return { error: 'Quiz not found' };
    }
    if (!quiz.AuthorID.includes(userId)) {
        return { error: 'Valid token is provided, but user is not an owner of this quiz' };
    }

    // 验证问题数据的有效性
    if (questionData.question.length < 5 || questionData.question.length > 50 ||
        questionData.answers.length < 2 || questionData.answers.length > 6 ||
        questionData.duration <= 0 || questionData.points < 1 || questionData.points > 10 ||
        questionData.answers.some(a => a.answer.length < 1 || a.answer.length > 30 || !a.correct)) {
        return { error: 'Invalid question data' };
    }

    const newQuestion = {
        question: questionData.question,
        questionId: Date.now(), // 简单使用时间戳作为ID
        duration: questionData.duration,
        points: questionData.points,
        answers: questionData.answers.map(a => ({ ...a, color: randomColor() })) // 为答案生成颜色
    };

    quiz.Questions.push(newQuestion);
    quiz.TimeLastEdited = new Date();

    setData(data);

    return { question: newQuestion };
}
export function getFinalResults(sessionId: number) {
    const data = getData();
    for (let quiz of data.quizzes) {
        let session = quiz.Sessions.find(s => s.SessionID === sessionId);
        if (session) {
            return session.Results || [];
        }
    }
    return []; // 如果找不到会话，返回空数组
}
export function generateCSV(sessionId: number) {
    const results = getFinalResults(sessionId);
    let csvContent = 'PlayerID,Score\n';
    results.forEach(result => {
        csvContent += `${result.playerId},${result.score}\n`;
    });
    return csvContent;
}
export function generateRandomName(): string {
    const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    const digits = '0123456789';
    let name = '';
    for (let i = 0; i < 5; i++) {
        name += letters.charAt(Math.floor(Math.random() * letters.length));
    }
    for (let i = 0; i < 3; i++) {
        name += digits.charAt(Math.floor(Math.random() * digits.length));
    }
    return name;
}


export function isValidSession(sessionId: number): boolean {
    const { quizzes } = getData();
    return quizzes.some(quiz => quiz.Sessions.some(session => session.SessionID === sessionId));
}

export function getSessionState(sessionId: number): string | null {
    const { quizzes } = getData();
    for (const quiz of quizzes) {
        const session = quiz.Sessions.find(s => s.SessionID === sessionId);
        if (session) return session.State;
    }
    return null;
}

export function generateUniqueName(): string {
    const data = getData();
    let newName = '';
    do {
        const letters = Array.from({ length: 5 }, () => String.fromCharCode(Math.floor(Math.random() * 26) + 97)).join('');
        const numbers = Array.from({ length: 3 }, () => Math.floor(Math.random() * 10)).join('');
        newName = letters + numbers;
    } while (data.users.some(u => u.FirstName === newName));
    return newName;
}

export function findSessionByPlayerId(data: Data, playerId: number): Session | undefined {
    return data.quizzes.flatMap(q => q.Sessions).find(s => s.Results?.some(r => r.playerId === playerId));
}